<template>
	<div>
		<div class="videolistbox" style="width: 100%;height: 100%;position: absolute;overflow-y: auto;"
			:style="{'--bgcolor':config.config.property.bgColor,'--color':config.config.property.color,'--titlecolor':config.config.property.titlecolor,'--borderColor': config.config.property.searchborderColor}">
			<div style="width: 91%;height: 96%;margin-left:4.5%;margin-top:4.5%;">
				<div style="margin-bottom: 10px;">
					<el-input :input-style="{ 'background': config.config.property.searchbgColor, 'color': config.config.property.searchtxtColor}"
						v-model="filterText" placeholder="输入关键字进行过滤">
					</el-input>
				</div>
				<div>
					<!-- <el-collapse v-model="activeNames" @change="handleChange">
						<el-collapse-item>
							<template #title>
								<span style="margin-left: 5px;">视频源</span>
							</template>
							<div> -->
								<el-tree ref="tree" class="filter-tree" :data="treeData" :props="defaultProps"
									:filter-node-method="filterNode" accordion show-icon @node-click="handleNodeClick"/>
							<!-- </div>
						</el-collapse-item>
				
					</el-collapse> -->
				</div>
			</div>
		</div>
	</div>
</template>
<script>
	import {
		EMIT_PARAMS_OBJ
	} from '@/utils/constant';
	import chartBase from '@/mixin/chart-base.js';
	import emitComponentBase from '@/mixin/emit-component-base.js';
	import dataModel from '@/models/panel-config-data.js';
	import {
		checkNegative
	} from '@/utils/util';
	import {
		mapState
	} from 'vuex';
	import config from './config/config';
	export default {
		name: 'videoList',
		// components: {},
		mixins: [chartBase, emitComponentBase],
		props: ['pareentId', 'widgetId', 'widgetInstanceId', 'widgetName', 'identifier', 'layout', 'w', 'h', 'Item'],
		data() {
			return {
				orgConfig: [],
				isNoData: false,
				isLoading: false,
				treeData: [{
					label: '一级 1',
					children: [{
						label: '二级 1-1',

					}]
				}, {
					label: '一级 2',
					children: [{
						label: '二级 2-1',

					}, {
						label: '二级 2-2',

					}]
				}, {
					label: '一级 3',
					children: [{
						label: '二级 3-1',

					}, {
						label: '二级 3-2',

					}]
				}],
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				filterText:''
			};
		},
		computed: {
			...mapState({}),
		},
		watch: {
			filterText(val) {
			    this.$refs.tree.filter(val);
			  }
		},
		created() {
			this.orgConfig = config;
			this.config = JSON.parse(JSON.stringify(this.orgConfig));
			this.chartId = `${this.widgetInstanceId}_01`;
		},
		mounted() {
			if (window.isLocalEnv) {
				this.loadWidget();
			}

		},
		methods: {
			filterNode(value, data) {
			    if (!value) return true;
			    return data.label.indexOf(value) !== -1;
			  },
			// 初始加载时 以及 编排面更改配置时 触发
			loadWidget(pageStatus) {
				this.pageStatus = pageStatus;
				this.updateConfigProperty();
				this.updateConfigData();
				if (window.isLocalEnv || this.emitComponentStatus) {
					this.updateParams(pageStatus);
					if (!this.isRealTime) {
						this.debounceGetData();
					}
				}
				this.afterLoadWidget();
				this.checkNegative(this.apiResult);
			},

			// 接收xvue发来的实时数据
			handleRealTimeCommunication(realTimeData) {
				if (this.config.config.property.isDebounce && this.isStopRealData) {
					return;
				}

				const result = this.getResult(realTimeData);
				if (this.isNoData || this.autoRefreshIsSameRes(result)) {
					this.isLoading = false;
					return;
				}
				const {
					data,
					property
				} = this.config.config;

				// api请求，拿到数据
				if (data.dataSourceType !== 'xMinerRedisRealTime') {
					this.getCorrectParams(this.params, data.dataSourceType); // 参数存入xvue，导出数据时使用
				}
				// this.apiResult = result;
				// this.lastParams = null;
				// this.sendDataToConfig(result);
				// const convertedData = convertData(result, property);
				// if (convertedData === -1) {
				//   this.$message.error(this.$demoi18n('view.dataSourceTypeErr'));
				//   this.setDataException();
				//   return;
				// }
				// this.generateChart(convertedData);
				// this.isLoading = false;
			},
			acceptEvtMsg(paramters, key, obj) {
				this.checkUpdateParams(obj);
			},
			checkUpdateParams(obj) {
				// 检查下是否和本组件有关
				const _obj = obj || {};
				let oo = {}
				let flag = false;
				for (const key in _obj) {
					if (key.indexOf(EMIT_PARAMS_OBJ) > -1) {
						const o = _obj[key];
						if (o.eventKey) {
							const event = this.config.events.find(e => e.type === 'in' && e.key === o.eventKey);
							if (event) {
								flag = true;
								oo = o
							}
							break;
						}
					}
				}
				if (flag) {
					// 和本组件有关再执行组件接收到事件后的相关操作
					console.log('_obj', _obj)
					console.log('oo', oo)

					this.isNoData = false;
					this.isLoading = true;
					this.autoRefresh();
					const alarm_id = oo?.parameters[oo?.keys[0]]
					let param = {
						code: 'alarm_id',
						value: alarm_id
					}
					let paramOo = [param]

					// api请求，拿到数据
					const {
						data
					} = this.config.config
					this.isLoading = true
					const method = `getChartData${data.dataSourceType}`;
					const trueParams = this.getCorrectParams(this.params, data.dataSourceType);
					trueParams = {
						...trueParams,
						params: paramOo,
					};

					dataModel[method](trueParams, data)
						.then(result => {



							// 重置数据异常状态
							this.resetAbnormalType();
							this.reportIfFieldsError(this.getParams()?.propertyMapping, result);
							if (this.autoRefreshIsSameRes(result)) {
								return;
							}

						})
						.catch(err => {
							this.handleChartDataError(err);
						})
						.finally(() => {
							this.isLoading = false;
						});
				}
			},

			handleNodeClick(data) {
				// console.log(data)
				if (data.children) {
					// 点击的是一级菜单，调用接口加载二级菜单数据（示例）
					console.log('一级')


				} else {
					// 点击的是二级菜单，处理数据（示例）
					console.log('二级')
					// chartClick(data)
					this.itemClick(data)
				}
			},
			getChartData() {
				console.log(1111)

				fetch(this.config.config.property.input + '/api/v1/device/list')
					.then(response => response.json())
					.then(data => {
						data.DeviceList.map(item => {
							item.children = []
							if (item.Name != '') {
								item.label = item.Name
							} else {
								item.label = item.CustomName
							}


						})
						this.treeData = data.DeviceList
						this.treeData = data.DeviceList
						console.log(this.treeData)
						this.treeData.map(item => {


							fetch(this.config.config.property.input + '/api/v1/device/channeltree?serial=' +
									item.ID)
								.then(response => response.json())
								.then(data => {
									data.map(items => {
										if (items.name != '') {
											items.label = items.name
										} else {
											items.label = items.customName
										}
									})
									item.children = data
								})
								.catch(error => console.error("Error:", error));
						})

					})
					.catch(error => console.error("Error:", error));
			},
			itemClick(params) {
				console.log(this.widgetInstanceId)
				const orgEvtKey = this.orgConfig.events[0].key
				const outEvt = this.config.events[0]
				const {
					key
				} = outEvt.parameters[0] // key: 对应xminer接口中的参数/编码
				const {
					paramKey
				} = outEvt // paramKey: 对应数据面板中的字段名，如s，y
				console.log('=======params============', params)
				const outObj = {
					emit_params_obj: {
						eventKey: outEvt.key,
						type: 'terms',
						keys: [key],
						parameters: {
							// [key]: params[paramKey],
							[key]: params,
						},
						widgetInstanceId: this.widgetInstanceId,
						sendTime: new Date().getTime(),
					},
				}
				console.log(outEvt)
				console.log(orgEvtKey, outObj)

				this.vsEmit(orgEvtKey, outObj);
				// console.log("===================",outObj)
				// xvue提供的emit方法，用于发出事件的
				// if (import.meta.env.PROD) {
				//   this.adapterComponent.emit(orgEvtKey, outObj)
				// } else {
				//   emit(orgEvtKey, outObj)
				// }


				// this.lastParams = params;
				// this.bindLowCodeChartClickCallback(params);

				// const outObj = {};
				// const evtKey = this.orgConfig.events[0].key || 'chart-click';
				// const { key } = this.orgConfig.events[0].parameters[0];
				// const { paramKey } = this.config.events[0]; // 字段名code

				// const keys = [this.config.events[0].parameters[0].key];
				// const parameters = {
				//   [keys[0]]: outObj[key],
				// };

				// outObj[EMIT_PARAMS_OBJ] = {
				//   eventKey: this.config.events[0].key,
				//   keys,
				//   type: 'terms',
				//   parameters,
				//   widgetInstanceId: this.widgetInstanceId,
				//   sendTime: new Date().getTime(),
				// };
				// console.log(evtKey,outObj)
				// this.vsEmit(evtKey, outObj);
















			},
			// getTooltip() {
			//   return {
			//     config: this.config.config.property.tooltip || {},
			//     vars: {},
			//     params: this.params,
			//     parentComp: this,
			//   };
			// },
			checkNegative,
			// itemClick(params) {
			// 	console.log(params)
			// 	this.chartClick(params);
			// 	if (params) {
			// 		this.sendAdvancedLinkagge({
			// 			...params
			// 		});
			// 	}
			// },
			// handleAsTooltip(filterRes) {
			// 	const {
			// 		property
			// 	} = this.config.config;
			// 	const convertedData = convertData(filterRes, property);
			// 	this.generateChart(convertedData);
			// },
		},
	};
</script>
<style lang="less" scoped>
	// 图表通用样式，主要有黑色loading 和 黑色 ‘没有数据’，样式名需一致
	@import '../../common/chart.less';
</style>
<style>
	/* 全局loading样式修改 */

	.chartMain .loading .el-loading-spinner .circular {
		width: 34px !important;
		height: 34px !important;
	}

	.chartMain .el-dialog__header {
		padding: 9px 20px 10px !important;
		background: #2a3352 !important;
		text-align: left;
		box-sizing: border-box;
		height: 50px;
		line-height: 32px;
	}

	.chartMain .el-dialog__title {
		text-align: left;
		/* font-size: 18px; */
		line-height: 18px !important;
		color: #b2d3fe !important;
	}

	.chartMain .el-dialog__body {
		padding: 10px 20px 30px 20px;
		background: #1a2032 !important;
		line-height: 24px;
		font-size: 14px;
	}

	.chartMain .el-dialog__headerbtn .el-dialog__close {
		color: #b2d3fe !important;
	}

	.chartMain .dialog-footer {
		text-align: right;
		margin-bottom: -14px;
		margin-right: 4px;
	}

	.chartMain .el-dialog__headerbtn {
		top: 15px;
		/* font-size: 18px; */
	}
</style>
<style scoped lang="less">
	/deep/.el-tree {
		background: var(--bgcolor) !important;
		color: var(--color);
		--el-tree-node-hover-bg-color: none !important;
	}
	/deep/.el-tree-node{
		border-top:1px solid RGBA(5, 27, 58, 1) ;
	}

	/deep/.el-input__wrapper {
		padding: 0 !important;
		background-color: rgba(255,255,255, 0) !important;
		box-shadow:0 0 0 1px var(--borderColor) !important;
		border-radius:0 !important;
	}
	/deep/.el-collapse {
		--el-collapse-border-color: none !important;
		--el-collapse-header-height: 48px;
		--el-collapse-header-bg-color: none !important;
		--el-collapse-header-text-color: var(--color) !important;
		--el-collapse-header-font-size: 13px;
		--el-collapse-content-bg-color: none !important;
		--el-collapse-content-font-size: 13px;
		--el-collapse-content-text-color: #fff !important;

	}

	/deep/.el-collapse-item__header {
		background-color: var(--titlecolor) !important;
		color: var(--color);
		height: 32px;
	}
	/deep/.el-tree-node__expand-icon{
		color: var(--color) !important;
	}

	// /deep/.el-tree-node__content:hover {
	// 	background-color: aqua !important;
	// }
	.videolistbox {
		background: url(./image/leftbgimg.png) no-repeat;
		background-size: 100% 100%;
	}
</style>